package com.xxhui.listviewdemo.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.xxhui.listviewdemo.Bean.ChatItemBean;
import com.xxhui.listviewdemo.R;

import java.util.List;

/**
 * Created by hui on 2016/7/20.
 */
public class ChatItemAdapter extends BaseAdapter {

    private static final String TAG = "ChatItemAdapter";
    private List<ChatItemBean> data;
    private LayoutInflater inflater;

    public ChatItemAdapter(Context context, List<ChatItemBean> data) {
        this.data = data;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public int getItemViewType(int position) {
        return data.get(position).getType();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Log.i(TAG, "getView: Position :" + i + "  " + data.get(i).toString());
        ViewHolder holder = null;
        if (view == null) {
            view = getView(i,view);
            holder = (ViewHolder) view.getTag();
        } else {
            holder = (ViewHolder) view.getTag();
            if(holder==null){
                holder = new ViewHolder();
                holder.type = -1;
            }
            if (holder.type != getItemViewType(i)) {
                view = getView(i,view);
                holder = (ViewHolder) view.getTag();
            }
        }
        ChatItemBean bean = data.get(i);
        holder.icon.setImageBitmap(bean.getIcon());
        holder.text.setText(bean.getText());
        return view;
    }

    public class ViewHolder {
        public ImageView icon;
        public TextView text;
        public int type;
    }

    public View getView(int i, View view){
        ViewHolder holder = new ViewHolder();
        switch (getItemViewType(i)){
            case 0:
                view = inflater.inflate(R.layout.chat_item_left, null);
                holder.icon = (ImageView) view.findViewById(R.id.icon_left);
                holder.text = (TextView) view.findViewById(R.id.text_left);
                break;
            case 1:
                view = inflater.inflate(R.layout.chat_item_right, null);
                holder.icon = (ImageView) view.findViewById(R.id.icon_right);
                holder.text = (TextView) view.findViewById(R.id.text_right);
                break;
            default:
                view = null;
                break;
        }
        holder.type = getItemViewType(i);
        view.setTag(holder);
        return view;
    }

}
